<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-23 14:44:33
 * @LastEditTime: 2023-02-16 10:07:38
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 审批列表
 * @Motto: Write the code. Change the world.
-->
<template>
  <div class="approval-list route-page">
    <section class="header">
      <a-page-header :class="notBack ? 'hide-back' : ''" title="审批列表" @back="goBack" />
    </section>
    <section class="content">
      <section class="filter">
        <a-input-search
          v-model:value="keywords"
          placeholder="请搜索租客、房号"
          style="width: 200px"
          @search="onSearch"
        />
      </section>
      <section class="tags" v-if="Object.keys(filterTags).length">
        <a-tag
          closable
          v-for="(tag, tagKey) in filterTags"
          :key="tagKey"
          color="blue"
          @close="closeFilterTag(tagKey)"
          class="mt-10"
        >
          {{ tag }}
        </a-tag>
        <a-tag color="blue" @click="clearFilter" style="cursor: pointer">
          清除选项
        </a-tag>
      </section>
      <section class="tabs">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane
            :key="tab.key"
            :tab="tab.name"
            v-for="tab of tabList"
          ></a-tab-pane>
        </a-tabs>
      </section>

      <section class="table">
        <a-table
          :columns="columnData"
          :data-source="dataList"
          bordered
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          rowKey="id"
          :customRow="customRow"
          :row-selection="activeKey == 'type_2' ? rowSelection : null"
        >
          <template #title>
            <a-row
              type="flex"
              align="middle"
              justify="space-between"
              class="plr-10"
            >
              <a-col
                class="mlr-10"
                style="padding-top: 5px; padding-bottom: 5px"
                >审批列表</a-col
              >
              <a-col class="ml-10">
                <a-button
                  type="primary"
                  @click="toApprove"
                  v-if="selectedRowKeys.length"
                >
                  批量审批
                </a-button>
              </a-col>
            </a-row>
          </template>
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'approve_overtime'">
              <span>{{ text || "--" }}</span>
            </template>
          </template>
        </a-table>
      </section>
    </section>

    <HandleApproval
      :visible="handleApprovalVisible"
      @onClose="handleApprovalClose"
      @submit="handleApprovalSubmit"
    />

    <!--  -->
    <a-modal
      title=""
      :visible="approvalLoading"
      centered
      :width="400"
      :closable="false"
      :destroyOnClose="true"
      :footer="null"
    >
      <a-row justify="center" class="mt-20">
        <a-spin v-if="approvalPadding" size="large" />
        <CheckCircleFilled v-else style="color: #52c41a; font-size: 36px" />
      </a-row>
      <a-row justify="center" class="mt-20">
        <div style="font-size: 20px; font-weight: bold">
          {{ approvalPadding ? "批量处理中" : "批量处理响应完成" }}
        </div>
      </a-row>
      <a-row justify="center" class="mt-20">
        <div style="color: #999">请耐心等待一段时间后刷新页面</div>
      </a-row>
      <a-row justify="end" class="mt-20">
        <a-button @click="closeApprovalLoading" type="primary">知道了</a-button>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { CheckCircleFilled } from "@ant-design/icons-vue";
import { Modal, notification } from "ant-design-vue";
import { defineComponent, ref, computed, watch, onActivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import request from "../../../common/utils/request";
import store from "../../../store";
import HandleApproval from "./modules/HandleApproval.vue";
import _ from "lodash";

export default defineComponent({
  name: "contractApprovalList",
  components: { HandleApproval, CheckCircleFilled },
  setup() {
    const $route = useRoute();
    let type = $route.query.type;

    //   搜索
    const keywords = ref("");
    const searchWords = ref("");
    const notBack = $route.query.noBack;
    const onSearch = () => {
      searchWords.value = keywords.value;
      page.value = 1;
      getDataList();
    };

    // 搜索条件展示
    const filterTags = computed(() => {
      const { processType, approveStatus } = initData.value;
      const { process_type_txt, work_type_txt, status_txt } =
        filteredInfo.value;
      let list = {};
      if (process_type_txt && process_type_txt.length) {
        list.process_type = "筛选：审批类型";
        if (processType && processType.length > 0) {
          let resultArr = [];
          process_type_txt.map((item) => {
            let result = processType.find((listItem) => listItem.key == item);
            if (result) {
              resultArr.push(result.name);
            }
          });
          list.process_type = "审批类型: " + resultArr.join();
        }
      }
      if (work_type_txt && work_type_txt.length) {
        list.work_type = "筛选：业务类型";
      }
      if (status_txt && status_txt.length) {
        list.status = "筛选：审批状态";
        if (approveStatus && approveStatus.length > 0) {
          let resultArr = [];
          status_txt.map((item) => {
            let result = approveStatus.find((listItem) => listItem.key == item);
            if (result) {
              resultArr.push(result.name);
            }
          });
          list.status = "审批状态: " + resultArr.join();
        }
      }
      if (sorterInfo.value.launch_time) {
        list.launch_time = "排序：发起时间";
      }
      if (searchWords.value) {
        list.keywords = `搜索：${searchWords.value}`;
      }
      return list;
    });
    const closeFilterTag = (key) => {
      if (key == "keywords") {
        keywords.value = searchWords.value = "";
      } else if (key == "launch_time") {
        sorterInfo.value = {};
      } else {
        filteredInfo.value = {};
      }
      page.value = 1;
      getDataList();
    };
    const clearFilter = () => {
      keywords.value = searchWords.value = "";
      filteredInfo.value = {};
      sorterInfo.value = {};
      page.value = 1;
      getDataList();
    };

    // tab
    const activeKey = ref();
    const tabList = ref([]);
    watch(activeKey, (val) => {
      if (val == "type_1") {
        keywords.value = searchWords.value = "";
        sorterInfo.value = {};
        filteredInfo.value = {
          status_txt: [1],
        };
        page.value = 1;
        getDataList();
      } else {
        clearFilter();
      }
    });

    // table
    const dataList = ref([]);
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const filteredInfo = ref({});
    const sorterInfo = ref({});
    const handleTableChange = (pager, filters, sorter) => {
      console.log("filters", filters);
      console.log("sorter", sorter);
      filteredInfo.value = filters;
      if (sorter.order) {
        sorterInfo.value = {
          [sorter.field]: sorter.order,
        };
      } else {
        sorterInfo.value = {};
      }
      page.value = pager.current;
      limit.value = pager.pageSize;
      getDataList();
    };

    const getDataList = () => {
      let params = {
        page: page.value,
        limit: limit.value,
        keywords: keywords.value,
        list_type: activeKey.value,
      };
      const { process_type_txt, work_type_txt, status_txt } =
        filteredInfo.value;
      params.process_type =
        process_type_txt && process_type_txt.length
          ? process_type_txt.join(",")
          : undefined;
      params.work_type =
        work_type_txt && work_type_txt.length
          ? work_type_txt.join(",")
          : undefined;
      params.status =
        status_txt && status_txt.length ? status_txt.join(",") : undefined;
      if (Object.keys(sorterInfo.value).length) {
        params.order = "launch_time";
        params.sort = sorterInfo.value.launch_time == "ascend" ? "asc" : "desc";
      }
      request.post("/org", "/workbench/approveList", params).then((res) => {
        dataList.value = res.list;
        total.value = res.total;
      });
    };

    const columnData = computed(() => {
      const { processType, workType, approveStatus } = initData.value;
      return [
        {
          title: "审批类型",
          dataIndex: "process_type_txt",
          filteredValue: filteredInfo.value.process_type_txt || null,
          filters:
            processType && processType.length
              ? processType.map((item) => ({
                  text: item.name,
                  value: item.key,
                }))
              : [],
        },
        {
          title: "业务类型",
          dataIndex: "work_type_txt",
          // filteredValue: filteredInfo.value.work_type_txt || null,
          // filters:
          //   workType && workType.length
          //     ? workType.map((item) => ({
          //         text: item.name,
          //         value: item.key,
          //       }))
          //     : [],
        },
        {
          title: "提交人",
          dataIndex: "cuser_name",
        },
        {
          title: "摘要",
          dataIndex: "abstract",
          width: 300,
        },
        {
          title: "发起时间",
          dataIndex: "launch_time",
          sorter: true,
          sortOrder: sorterInfo.value.launch_time || null,
        },
        {
          title: "审批状态",
          dataIndex: "status_txt",
          filteredValue: filteredInfo.value.status_txt || null,
          filters:
            approveStatus && approveStatus.length
              ? approveStatus.map((item) => ({
                  text: item.name,
                  value: item.key,
                }))
              : [],
        },
        {
          title: "当前审批人",
          dataIndex: "now_approve_name",
        },
        {
          title: "审批完结时间",
          dataIndex: "approve_overtime",
          key: "approve_overtime",
        },
      ];
    });

    let initData = ref({});
    const init = () => {
      store.dispatch("SetApprovalListInit").then((data) => {
        initData.value = data;
        if (data.approveTab.length) {
          activeKey.value = type || data.approveTab[0].key;
          tabList.value = data.approveTab;
        }
      });
    };
    onActivated(() => {
      if (activeKey.value && $route.query.type && type != $route.query.type) {
        type = $route.query.type;
        activeKey.value = type;
      }

      selectedRowKeys.value = [];

      if (activeKey.value == "type_1") {
        keywords.value = searchWords.value = "";
        sorterInfo.value = {};
        filteredInfo.value = {
          status_txt: [1],
        };
        page.value = 1;
        getDataList();
      }
    });

    init();

    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };
    // 点击行
    const $router = useRouter();
    const handleTableRowClick = (record) => {
      if (record.status >= 4) {
        // 已撤回 关闭并删除
        Modal.warning({
          title: () => "提示",
          centered: true,
          content: "当前合同审批已被撤回或删除，无法查看详情！",
        });
        return;
      }
      $router.push({
        name: "contractApproval",
        query: { contractId: record.contract_id, approveId: record.id },
      });
    };

    const goBack = () => {
      type = "";
      $router.replace("/index");
      // actions.setGlobalState({
      //   goBack: true,
      // });
    };

    const selectedRowKeys = ref([]);

    const onSelectedRowChange = (keys) => {
      console.log(keys);
      if (keys.length > 100) {
        notification.warning({
          message: "警告",
          description: "您最多可勾选100项",
        });
        return;
      }
      selectedRowKeys.value = keys;
    };
    let selectedRows = [];
    watch(
      () => selectedRowKeys.value,
      (keyList) => {
        let rowArr = [];
        let rowKeys = [];
        selectedRows.forEach((row) => {
          if (keyList.includes(row.id)) {
            rowArr.push(row);
            rowKeys.push(row.id);
          }
        });
        dataList.value.forEach((item) => {
          if (keyList.includes(item.id) && !rowKeys.includes(item.id)) {
            rowArr.push(item);
          }
        });
        selectedRows = rowArr;
      }
    );

    const rowSelection = computed(() => ({
      selectedRowKeys: selectedRowKeys.value,
      onChange: onSelectedRowChange,
    }));

    const handleApprovalVisible = ref(false);
    const toApprove = () => {
      handleApprovalVisible.value = true;
    };

    const handleApprovalClose = () => {
      handleApprovalVisible.value = false;
    };

    const approvalLoading = ref(false);
    const approvalPadding = ref(false);

    const handleApprovalSubmit = (params, status) => {
      approvalPadding.value = true;
      let submitParams = {
        ...params,
        status: status,
        approve_ids: _.cloneDeep(selectedRowKeys.value),
        needMsg: true,
      };
      handleApprovalVisible.value = false;
      selectedRowKeys.value = [];
      approvalLoading.value = true;
      request
        .post("/org", "/contract/batchApprove", { ...submitParams })
        .then((res) => {
          approvalPadding.value = false;
        });
    };

    const closeApprovalLoading = () => {
      approvalLoading.value = false;
      approvalPadding.value = false;
      page.value = 1;
      getDataList();
    };

    return {
      keywords,
      activeKey,
      columnData,
      dataList,
      tabList,
      loading,
      pagination,
      filterTags,
      customRow,
      onSearch,
      handleTableChange,
      closeFilterTag,
      clearFilter,
      goBack,
      rowSelection,
      selectedRowKeys,
      handleApprovalVisible,
      toApprove,
      handleApprovalClose,
      handleApprovalSubmit,
      approvalLoading,
      approvalPadding,
      closeApprovalLoading,
      notBack,
    };
  },
});
</script>

<style lang="less" scoped>
.approval-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    background: #fff;
    height: 60px;
    overflow: hidden;
    &:deep(.ant-page-header) {
      padding: 10px 20px 0 20px;
    }
  }
  .content {
    flex: 1;
    width: 100%;
    height: calc(100% - 60px);
    padding: 10px;
    box-sizing: border-box;
    overflow-y: auto;
    .tags {
      margin-top: 10px;
    }
    .tabs {
      background: #fff;
      margin-top: 20px;
      &:deep(.ant-tabs-bar) {
        margin: 0px;
      }
    }
    .table {
      margin-top: 10px;
    }
  }

  :deep(.ant-table-title) {
    padding: 12px;
  }
}

.hide-back {
  :deep(.ant-page-header-back) {
    display: none;
  }
}
</style>
